<template>
    <el-form ref="formRef" :model="form" label-width="80px">
        <el-form-item label="商品名" prop="name">
            <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="price">
            <el-input v-model="form.price"></el-input>
        </el-form-item>
        <el-form-item label="商品分类" prop="cid">
            <el-select v-model="form.cid" placeholder="请选择分类">
                <el-option v-for="item in goodlist" :key="item.id" :label="item.cname" :value="item.id" />
            </el-select>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" v-if="form.id == 0" @click="add"
                >添加</el-button
            >
            <el-button type="primary" v-else @click="edit">修改</el-button>
            <el-button type="info" @click="resetForm()">重置</el-button>
        </el-form-item>
    </el-form>
</template>
<script setup>
import {ref,reactive,onMounted } from 'vue'
import { findGoods, updateGoods,getCategoryList } from '../api/api';
import {addGoods} from '../api/api'
const props=defineProps({
    id:{
        type:Number
    }
})
const formRef=ref()
const goodlist=ref([])
const emit = defineEmits("success");
const form=reactive({
    id:props.id,
    name:'',
    price:'',
    cid:''
})
onMounted(()=>{
    goodslist()
})
const resetF=id=>{
    form.id=id;
    resetForm()
}
defineExpose({resetF})
const resetForm=()=>{
    formRef.value.resetFields();
    goodslist();
}
const goodslist=async()=>{
    if (form.id) {
        const data = await findGoods( form.id );
        Object.assign(form, data);
    }
    goodlist.value =await getCategoryList();
}
const edit=async(formRef)=>{
    if(await updateGoods(form)){
        emit('success')
    }
}
const add=async()=>{
    const data = {
        name: form.name,
        price: form.price,
        cid: form.cid,
    };
    if (await addGoods(data)) {
        emit("success");
    }
}
</script>